<template>
  <div class="flexContent">
    <!-- 销售订单报表 -->
    <div class="searchBox">
      <el-form ref="form" :model="form" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="门店">
                  <el-select @click.native="getShopEasy" v-model="form.storeId" placeholder="请选择门店" style="width: 95%;"
                    filterable clearable popper-class="eloption" @change="changeShop">
                    <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="订单编号">
                  <el-input v-clearEmoji v-model.trim="form.orderNum" style="width: 95%;" clearable
                    placeholder="请输入订单编号..." @keyup.enter.native="searchFn" @clear="resetForm" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="下单方式">
                  <el-select v-model="form.orderMethods" popper-class="eloption" clearable style="width: 95%;"
                    placeholder="请选择">
                    <el-option value="" label="全部" />
                    <el-option value="0" label="扫码支付" />
                    <el-option value="1" label="现金订单" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="收银员">
                  <el-input v-clearEmoji v-model.trim="form.cashierName" style="width: 95%;" clearable
                    placeholder="请输入收银员..." @keyup.enter.native="searchFn" @clear="resetForm" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="10" :xl="6">
                <el-form-item label="订单时间">
                  <el-date-picker v-model="date" type="daterange" unlink-panels range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 95%;" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetForm('form')" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" @click="exportSell" v-has="'orderReport_export'">导出</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="98%"
          size="medium" align="center" :footer-method="getSummaries" show-footer>
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column field="storeName" title="门店名称" :min-width="elTableAdaptationWidth('storeName', tableData)" />
          <vxe-column field="orderNum" title="订单编号" :min-width="elTableAdaptationWidth('orderNum', tableData) + 20" />
          <vxe-column field="cashierName" title="收银员" :min-width="elTableAdaptationWidth('cashierName', tableData)" />
          <vxe-column field="orderAmount" title="订单金额（元）" min-width="150" />
          <vxe-column field="erpProfit" title="供应链货款（元）" min-width="150" />
          <vxe-column field="storeProfit" title="门店货款（元）" min-width="150" />
          <vxe-column field="storeOrderProfit" title="门店利润（元）" min-width="150" />
          <vxe-column field="fee" title="手续费（元）" min-width="150" />
          <vxe-column field="discountMoney" title="整单优惠金额（元）" min-width="180" />
          <vxe-column field="orderMethods" title="下单方式" min-width="150">
            <template v-slot="{ row }">
              <span v-if="row.orderMethods == '0'">扫码支付</span>
              <span v-if="row.orderMethods == '1'">现金支付</span>
            </template>
          </vxe-column>
          <vxe-column field="payTime" title="订单时间" min-width="150">
            <template v-slot="{ row }">
              <div>
                {{ row.payTime | parseTime }}
              </div>
            </template>
          </vxe-column>
          <vxe-column fixed="right" width="100" title="操作" v-if="$showFn(['orderReport_detail'])">
            <template v-slot="{ row }">
              <el-button type="text" style="margin-right: 10px; color: rgb(0, 132, 255)"
                @click="detail(row)">详情</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page.sync="page.pageNum" background :page-sizes="$pageSizes"
          :page-size.sync="page.pageSize" layout="total,->, sizes, prev, pager, next, jumper" :total="page.total"
          @size-change="changePageSize" @current-change="getOrderReportList" />
      </div>
    </div>

    <el-dialog :visible.sync="dialogTableVisible" title="订单详情">
      <div>
        <div class="inner">
          <el-table border :data="dialogArr" class="tablebox" style="margin-bottom: 50px" size="medium">
            <el-table-column prop="name" label="商品名称" align="center" min-width="220" />
            <el-table-column prop="type" label="商品类型" align="center" width="100">
              <template v-slot="{ row }">
                <span v-if="row.type == '0'">标品</span>
                <span v-if="row.type == '1'">非标品</span>
                <span v-if="row.type == '2'">自营</span>
                <span v-if="row.type == '3'">临时</span>
                <span v-if="row.type == '4'">期初</span>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="数量" align="center" width="100" />
            <el-table-column prop="sellPrice" align="center" label="门店售价" min-width="100" />
            <el-table-column prop="outboundPrice" align="center" label="采购价" min-width="100">
              <template v-slot="{ row }">
                <span v-if="+row.outboundPrice == 0">0</span>
                <span v-else>{{ row.outboundPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="profitAmount" align="center" label="商品利润" />
          </el-table>
        </div>
      </div>
      <div slot="footer">
        <el-button class="celBtn" @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import dayjs from 'dayjs';
import { reqOrderReportList, exportOrderReport, reqOrderDetail } from "@/api/report";
import { getShopEasy } from '@/api/shop';
export default {
  name: "OrderReport",
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      storeList: [],

      date: [],
      form: {
        orderNum: "",
        storeId: "",
        cashierName: "",
        orderMethods: ''
      },
      allDataArr: [],
      tableData: [],
      isSearch: false,
      dialogTableVisible: false,
      fieldSort: ['seq', 'storeName', 'orderNum', 'cashierName', 'orderAmount', 'erpProfit', "storeProfit", "storeOrderProfit", "fee", 'discountMoney', 'orderMethods', "payTime", "right"],
      dialogArr: [],
    };
  },
  computed: {
    minDate() {
      if (this.date == null) {
        return "";
      }
      if (this.date.length > 0) {
        return this.date[0];
      } else {
        return "";
      }
    },
    maxDate() {
      if (this.date == null) {
        return "";
      }
      if (this.date.length > 0) {
        return this.date[1];
      } else {
        return "";
      }
    },
  },
  created() {
    let t1 = dayjs().format('YYYY-MM-DD');
    this.date = [t1, t1]
    console.log('2222', this.date);
  },
  mounted() {
    this.getOrderReportList();

  },
  methods: {
    async getShopEasy() {
      let res = await getShopEasy();
      if (res.code === 200) {
        this.storeList = res.data.store;
      }
    },
    async getOrderReportList() {
      console.log(this.form.storeId, "@@@@@@@@@@@");
      let { orderNum, storeId, cashierName, orderMethods } = this.form;
      let { maxDate, minDate } = this;
      let { pageNum, pageSize } = this.page;
      if (!this.isSearch) {
        // maxDate = '';
        // maxDate = '';
        orderNum = '';
        cashierName = '';
      }
      let reqObj = { storeId, pageNum, pageSize, minDate, maxDate, orderNum, cashierName, orderMethods };
      let res = await reqOrderReportList(reqObj);
      if (res.code === 200) {
        this.tableData = res.data.pageInfo.list;
        let $table = null;
        $table = this.$refs.xTable1
        let resArr = [];
        let allCountObj = {
          erpProfit: res.data.erpProfit,
          fee: res.data.fee,
          discountMoney: res.data.discountMoney,
          orderAmount: res.data.orderAmount,
          storeProfit: res.data.storeProfit,
          storeOrderProfit: res.data.storeOrderProfit,
        };
        this.allDataArr = [];
        this.fieldSort.forEach(e => {
          if (e == 'seq') {
            resArr.push('合计');
          } else if (allCountObj[e] == null) {
            resArr.push('-');
          } else {
            resArr.push(allCountObj[e]);
          }
        });
        this.allDataArr.push(resArr);
        $table.loadData(this.tableData);
        this.page.total = res.data.pageInfo.total;
      }
    },
    searchFn() {
      this.page.pageNum = 1;
      this.isSearch = true;
      this.getOrderReportList();
    },
    resetForm() {
      this.page.pageNum = 1;
      this.page.pageSize = 20;
      this.isSearch = false;
      this.form = {
        storeId: "",
        cashierName: "",
        orderNum: "",
        orderMethods: ''
      };
      // let t1 = dayjs().format('YYYY-MM-DD');
      this.date = [1]
      this.getOrderReportList();
    },
    // 修改每页几条
    changePageSize() {
      this.page.pageNum = 1;
      this.getOrderReportList();
    },
    exportSell() {
      this.$confirm(`确认导出数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let { orderNum, storeId, cashierName, orderMethods } = this.form;
        let { maxDate, minDate } = this;
        let reqObj = { orderNum, storeId, minDate, maxDate, cashierName, orderMethods };
        let response = await exportOrderReport(reqObj);
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    },
    changeShop() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      }
      this.getOrderReportList();
    },
    async detail(row) {
      this.dialogTableVisible = true;
      let res = await reqOrderDetail({ id: row.id })
      if (res.code === 200) {
        this.dialogArr = res.data;
      }
    },
    close() {
      this.dialogTableVisible = false;
      this.dialogArr = [];
    },
    getSummaries() {
      return this.allDataArr;
    }
  },
};
</script>

<style lang="scss" scoped></style>
